<template>
	<div>
		<n-button @click="resetOrder" style="margin-bottom: 10px;">重置顺序</n-button>
		<vue-draggable v-if="isShow" handle=".handle" v-model="sortedData" tag="div" target=".n-data-table-tbody" animation="200">

			<!--			<n-data-table :columns="columns" :data="sortedData" virtual-scroll :bordered="true"/>-->
			<n-data-table
				ref="tableRef"
				:row-key="row=>row.label"
				virtual-scroll
				bordered
				:single-line="false"
				:single-column="false"
				:columns="columns"
				:data="sortedData"
				size="medium"
			/>

		</vue-draggable>
	</div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {VueDraggable} from 'vue-draggable-plus';

const columns = [
	{title: 'index', key: 'index', className: "handle"},
	{title: 'Label', key: 'label'},
	{title: 'Value 1', key: 'value1'},
	{title: 'Value 2', key: 'value2'}
];

const initialData = Array.from({length: 271}, (_, i) => ({
	index: i + 1,
	label: `Row ${i + 1}`,
	value1: Math.floor(Math.random() * 100),
	value2: Math.floor(Math.random() * 100),
}));

const sortedData = ref([]);

function updateArrayByKey(originalArray, updateArray, key) {
	if (!originalArray || originalArray.length === 0) {
		return updateArray;
	}

	const updateMap = new Map(updateArray.map(item => [item[key], item]));

	return originalArray.map(item => updateMap.get(item[key]) || item);
}

const refreshData = () => {
	// 把数据刷新改成新 newData 和oldData而非这么简单的自定义
	if (sortedData.value.length === 0) {
		sortedData.value = initialData
		return
	}
	sortedData.value = updateArrayByKey(
		sortedData.value,
		Array.from({length: 271}, (_, i) => ({
			index: i + 1,
			label: `Row ${i + 1}`,
			value1: Math.floor(Math.random() * 100),
			value2: Math.floor(Math.random() * 100),
		})),
		"label"
	)
};
const isShow = computed(() => sortedData.value.length > 0)
const resetOrder = () => {
	sortedData.value = [...initialData];
};
let count = ref(0)
onMounted(() => {
	setInterval(() => count.value += 1, 1000);
	watch(count, (newValue, oldValue) => {
		refreshData()
	})
});

</script>

<style scoped>
.n-data-table {
	margin-bottom: 5px;
}
</style>